//
//  LoginViewController.m
//  田园
//
//  Created by 范明星 on 16/4/16.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "LoginViewController.h"
#import "userManager.h"
#import <AFNetworking/AFNetworking.h>
#import "RegistViewController.h"
#import "RootTabBatController.h"
#import "SpecialViewController.h"

//第三方登陆
#import <BmobSDK/BmobFile.h>
#import <BmobSDK/Bmob.h>
#import "UMSocial.h"




@interface LoginViewController ()
@property (strong, nonatomic) IBOutlet UITextField *name;
@property (strong, nonatomic) IBOutlet UITextField *password;
@property(nonatomic,strong)UIImageView *headImage;//QQ用户的头像
@property(nonatomic,copy)NSString *namestring;//用户的名称
@end

@implementation LoginViewController






//登陆
- (void)requestData {
 
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:@"http://app.htxq.net/servlet/UserCustomerServlet" parameters:@{@"action":@"login", @"password":self.password.text,  @"user":self.name.text} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSLog(@"aaa%@",dic);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([dic[@"status"] intValue] == 0) {
                NSString *msg = dic[@"msg"];
                NSLog(@"%@", msg);
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"登陆失败" message:msg preferredStyle:UIAlertControllerStyleAlert];
                [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [alertVC dismissViewControllerAnimated:YES completion:nil];
                }]];
                [self presentViewController:alertVC animated:YES completion:nil];
            }else{
                NSLog(@"登陆成功");
                [userManager saveuserID:dic[@"result"][@"id"] ];

                RootTabBatController *root = [[RootTabBatController alloc] init];
                [self presentViewController:root animated:YES completion:nil];
                [userManager saveserMobile:dic[@"result"][@"mobile"]];
                [userManager savePassWord:dic[@"result"][@"password"]];
            }
        });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
 
}

//返回到主界面
- (IBAction)back:(id)sender {
    RootTabBatController *root = [[RootTabBatController alloc] init];
    
    [self presentViewController:root animated:YES completion:nil];
   
   

}



//登陆按钮
- (IBAction)Login:(id)sender {
    [self  requestData];
   
}

//跳转注册界面
- (IBAction)EnterRegist:(id)sender {
    RegistViewController *registVC = [[RegistViewController alloc] init];
    [self presentViewController:registVC animated:YES completion:nil];
}

/*
- (void)changeLoginTextFiledColor
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSForegroundColorAttributeName] = [UIColor ]
    //NSAttributedString带有属性的文字，（富文本技术）；
    NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"手机号" attributes:<#(nullable NSDictionary<NSString *,id> *)#>];
    self.PhoneNumberTextFiled.attributedPlaceholder =
}
*/

//QQ登陆
- (IBAction)loginByQQ:(id)sender {
    
    //name 平台属性， platform平台标识
    UMSocialSnsPlatform *snsplatForm = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    //处理点击登陆事件后的block对象
    //UMSocialResponseEntity返回的状态对象，可以通过此对象获取返回类型、返回结果、返回数据等
    snsplatForm.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response){
        //获取QQ用户名， UID, token等
        //代表发送结果，UMSResponseCodeSuccess代表成功，参看上面的定义
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            //用户微博账户对象，对象数据从授权账号所对应的微博平台获取
            UMSocialAccountEntity *snsAccount  = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            
            //获取用户头像信息
            [self.headImage sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];//用户微博的头像的URL
            //保存用户的头像
            [userManager saveuserHeadImage:self.headImage.image];
            //获取名称,并保存
            self.namestring = snsAccount.userName;
            [userManager saveuserName:self.namestring];
            
            //得到的新浪微博授权信息，请按照例子来生成NSDictionary
            NSDate *date = [NSDate dateWithTimeInterval:ExpirationDate sinceDate:[NSDate date]];
            NSDictionary *dic = @{@"access_token": snsAccount.accessToken, @"uid":snsAccount.usid, @"expitionData":date };
            //通过授权信息注册登陆
            [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:(BmobSNSPlatformSinaWeibo) block:^(BmobUser *user, NSError *error) {
                [user setObject:self.namestring forKey:@"name"];
                [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    
                }];
            }];
        }
        
    } );
}

//新浪登陆
- (IBAction)LoginBySocinla:(id)sender {
    UMSocialSnsPlatform *platform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    platform.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina completion:^(UMSocialResponseEntity *response) {
                
                //获取用户的头像信息
                [self.headImage sd_setImageWithURL:[NSURL URLWithString:[response.data objectForKey:@"profile_image_url"]]];

                [userManager saveuserHeadImage:self.headImage.image];
                //用户名
                self.namestring = response.data[@"screen_name"];
                [userManager saveuserName:self.namestring];
                
                NSDate *date = [NSDate dateWithTimeInterval:ExpirationDate sinceDate:[NSDate date]];
                //得到的新浪微博授权信息，请按照例子来生成NSdaticonary
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                
                NSDictionary *dic = @{@"access_token":snsAccount.accessToken, @"uid":snsAccount.usid, @"expirationDate":date};
                
                //通过授权信息注册登陆
                [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformSinaWeibo block:^(BmobUser *user, NSError *error) {
                    [user setObject:self.namestring forKey:@"name"];
                    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        
                    }];
                }];
            }];
            
            
            
            
        }
        
    });
}

//微信登陆
- (IBAction)loginByWeChat:(id)sender {
    
    UMSocialSnsPlatform *snsplatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    snsplatform.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *accountEntity = [[UMSocialAccountManager socialAccountDictionary] objectForKey:UMShareToWechatSession];
            //获取头像信息
            [self.headImage sd_setImageWithURL:[NSURL URLWithString:accountEntity.iconURL]];
            [userManager saveuserHeadImage:self.headImage.image];
            self.namestring = accountEntity.userName;
            NSDate *date = [NSDate dateWithTimeInterval:ExpirationDate sinceDate:[NSDate date]];
            NSDictionary *dic = @{@"access_token":accountEntity.accessToken, @"usid":accountEntity.usid, @"expirationDate":date};
            [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformSinaWeibo block:^(BmobUser *user, NSError *error) {
                [user setObject:self.namestring forKey:@"name"];
                [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    
                }];
            }];
        }
    });
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view from its nib.
}


//让当前控制器的状态栏为白色
- (UIStatusBarStyle) preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
    
   
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
